<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">
  <link rel="alternate" href="/blog/atom.xml" title="大猪" type="application/atom+xml">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '7.5.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="属性   日常开发中，我们可以利用**@property**来创建一个属性，而该属性包含了一个成员变量，并且自动生成了get和set方法，也可以这样来解释：">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS关于属性的讲解">
<meta property="og:url" content="https://rogueandy.gitee.io/blog/2019/12/03/iOS%E5%85%B3%E4%BA%8E%E5%B1%9E%E6%80%A7%E7%9A%84%E8%AE%B2%E8%A7%A3/index.html">
<meta property="og:site_name" content="大猪">
<meta property="og:description" content="属性   日常开发中，我们可以利用**@property**来创建一个属性，而该属性包含了一个成员变量，并且自动生成了get和set方法，也可以这样来解释：">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-12-03T05:58:01.000Z">
<meta property="article:modified_time" content="2019-12-03T07:25:58.935Z">
<meta property="article:author" content="大钟">
<meta property="article:tag" content="iOS">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://rogueandy.gitee.io/blog/2019/12/03/iOS%E5%85%B3%E4%BA%8E%E5%B1%9E%E6%80%A7%E7%9A%84%E8%AE%B2%E8%A7%A3/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>iOS关于属性的讲解 | 大猪</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">大猪</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">Dazhong</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">4</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">10</span></a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/RogueAndy" class="github-corner" title="点击有彩蛋~" aria-label="点击有彩蛋~" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://rogueandy.gitee.io/blog/blog/2019/12/03/iOS%E5%85%B3%E4%BA%8E%E5%B1%9E%E6%80%A7%E7%9A%84%E8%AE%B2%E8%A7%A3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/userimg.jpeg#/images/avatar.gif">
      <meta itemprop="name" content="大钟">
      <meta itemprop="description" content="Dazhong">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="大猪">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          iOS关于属性的讲解
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2019-12-03 13:58:01 / 修改时间：15:25:58" itemprop="dateCreated datePublished" datetime="2019-12-03T13:58:01+08:00">2019-12-03</time>
            </span>

          
            <span id="/blog/2019/12/03/iOS%E5%85%B3%E4%BA%8E%E5%B1%9E%E6%80%A7%E7%9A%84%E8%AE%B2%E8%A7%A3/" class="post-meta-item leancloud_visitors" data-flag-title="iOS关于属性的讲解" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2019/12/03/iOS%E5%85%B3%E4%BA%8E%E5%B1%9E%E6%80%A7%E7%9A%84%E8%AE%B2%E8%A7%A3/#comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2019/12/03/iOS%E5%85%B3%E4%BA%8E%E5%B1%9E%E6%80%A7%E7%9A%84%E8%AE%B2%E8%A7%A3/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="属性"><a href="#属性" class="headerlink" title="属性"></a>属性</h2><p>   日常开发中，我们可以利用**<font color="#b83650"><code>@property</code></font>**来创建一个属性，而该属性包含了一个成员变量，并且自动生成了get和set方法，也可以这样来解释：</p><a id="more"></a>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">@property属性 &#x3D; setMethod + getMethod + 成员变量var</span><br></pre></td></tr></table></figure>
<p>   当我们声明一个属性username的时候，在编译阶段编译器会自动给对象添加一个成员变量<code>_username</code>（注意会自动生成下划线，下一段落会提到这一点）以及赋予其方法**<font color="#b83650"><code>- (void)setUsername:(NSString *)username</code></font><strong>和</strong><font color="#b83650"><code>- (NSString *)username</code></font>**。</p>
<p>   由于这个过程是编译阶段自动合成的，所以对于我们来说是隐藏了这步骤，而且添加成员变量也是有前提的，比如**<font color="#b83650"><code>@property (nonatomic, strong) NSString *username</code></font><strong>，定义该属性之后，会自动生成</strong><font color="#b83650"><code>_username</code><strong>带有下划线的成员变量，我们也是可以在代码中直接使用该成员变量，如果在同一时期，我们也写入了</strong><font color="#b83650"><code>_username</code>**这个样的变量，那么久重复了，没有意义了。<br>   这里将给出示例，请注意里面注释的代码</font></font></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line">#import &quot;TestController.h&quot;</span><br><span class="line">#include &lt;objc&#x2F;runtime.h&gt;</span><br><span class="line"></span><br><span class="line">@interface TestController () &#123;</span><br><span class="line">    NSString *age;</span><br><span class="line">&#x2F;&#x2F;    NSString *_username;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@property (nonatomic, strong) NSString *username;</span><br><span class="line"></span><br><span class="line">- (void)getPhone;</span><br><span class="line"></span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation TestController</span><br><span class="line"></span><br><span class="line">- (void)getPhone &#123;</span><br><span class="line">    NSLog(@&quot;this user phone is 11012010086&quot;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (void)noHeaderMethod &#123;</span><br><span class="line">    NSLog(@&quot;this is no header method&quot;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (void)viewDidLoad &#123;</span><br><span class="line">    [super viewDidLoad];</span><br><span class="line">    </span><br><span class="line">    self.view.backgroundColor &#x3D; [UIColor whiteColor];</span><br><span class="line">    </span><br><span class="line">    unsigned int count &#x3D; 0;</span><br><span class="line">    Ivar *vars &#x3D; class_copyIvarList([self class], &amp;count);</span><br><span class="line">    for(unsigned int i &#x3D; 0; i &lt; count; i++) &#123;</span><br><span class="line">        const char *var_name &#x3D; ivar_getName(vars[i]);</span><br><span class="line">        NSLog(@&quot;成员变量名称------%s\n&quot;, var_name);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    Method *methods &#x3D; class_copyMethodList([self class], &amp;count);</span><br><span class="line">    for(unsigned int i &#x3D; 0; i &lt; count; i++) &#123;</span><br><span class="line">        SEL method_name &#x3D; method_getName(methods[i]);</span><br><span class="line">        NSLog(@&quot;方法名-----%@&quot;, NSStringFromSelector(method_name));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">2019-12-03 14:44:40.195125+0800 DZWebLocalDemo[1532:33451] 成员变量名称------age</span><br><span class="line"></span><br><span class="line">2019-12-03 14:44:40.195274+0800 DZWebLocalDemo[1532:33451] 成员变量名称------_username</span><br><span class="line"></span><br><span class="line">2019-12-03 14:44:40.195377+0800 DZWebLocalDemo[1532:33451] 方法名-----getPhone</span><br><span class="line">2019-12-03 14:44:40.195459+0800 DZWebLocalDemo[1532:33451] 方法名-----noHeaderMethod</span><br><span class="line">2019-12-03 14:44:40.195520+0800 DZWebLocalDemo[1532:33451] 方法名-----.cxx_destruct</span><br><span class="line">2019-12-03 14:44:40.195595+0800 DZWebLocalDemo[1532:33451] 方法名-----setUsername:</span><br><span class="line">2019-12-03 14:44:40.195659+0800 DZWebLocalDemo[1532:33451] 方法名-----username</span><br><span class="line">2019-12-03 14:44:40.195746+0800 DZWebLocalDemo[1532:33451] 方法名-----viewDidLoad</span><br></pre></td></tr></table></figure>

<p>   接下来，我们将放开上面注释的代码，看一下的打印输出</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line">#import &quot;TestController.h&quot;</span><br><span class="line">#include &lt;objc&#x2F;runtime.h&gt;</span><br><span class="line"></span><br><span class="line">@interface TestController () &#123;</span><br><span class="line">    NSString *age;</span><br><span class="line">    NSString *_username;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@property (nonatomic, strong) NSString *username;</span><br><span class="line"></span><br><span class="line">- (void)getPhone;</span><br><span class="line"></span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">@implementation TestController</span><br><span class="line"></span><br><span class="line">- (void)getPhone &#123;</span><br><span class="line">    NSLog(@&quot;this user phone is 11012010086&quot;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (void)noHeaderMethod &#123;</span><br><span class="line">    NSLog(@&quot;this is no header method&quot;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (void)viewDidLoad &#123;</span><br><span class="line">    [super viewDidLoad];</span><br><span class="line">    </span><br><span class="line">    self.view.backgroundColor &#x3D; [UIColor whiteColor];</span><br><span class="line">    </span><br><span class="line">    unsigned int count &#x3D; 0;</span><br><span class="line">    Ivar *vars &#x3D; class_copyIvarList([self class], &amp;count);</span><br><span class="line">    for(unsigned int i &#x3D; 0; i &lt; count; i++) &#123;</span><br><span class="line">        const char *var_name &#x3D; ivar_getName(vars[i]);</span><br><span class="line">        NSLog(@&quot;成员变量名称------%s\n&quot;, var_name);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    Method *methods &#x3D; class_copyMethodList([self class], &amp;count);</span><br><span class="line">    for(unsigned int i &#x3D; 0; i &lt; count; i++) &#123;</span><br><span class="line">        SEL method_name &#x3D; method_getName(methods[i]);</span><br><span class="line">        NSLog(@&quot;方法名-----%@&quot;, NSStringFromSelector(method_name));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br><span class="line"></span><br><span class="line">2019-12-03 14:45:38.439313+0800 DZWebLocalDemo[1554:34308] 成员变量名称------age</span><br><span class="line"></span><br><span class="line">2019-12-03 14:45:38.439435+0800 DZWebLocalDemo[1554:34308] 成员变量名称------_username</span><br><span class="line"></span><br><span class="line">2019-12-03 14:45:38.439546+0800 DZWebLocalDemo[1554:34308] 方法名-----getPhone</span><br><span class="line">2019-12-03 14:45:38.439617+0800 DZWebLocalDemo[1554:34308] 方法名-----noHeaderMethod</span><br><span class="line">2019-12-03 14:45:38.439678+0800 DZWebLocalDemo[1554:34308] 方法名-----.cxx_destruct</span><br><span class="line">2019-12-03 14:45:38.439832+0800 DZWebLocalDemo[1554:34308] 方法名-----setUsername:</span><br><span class="line">2019-12-03 14:45:38.440014+0800 DZWebLocalDemo[1554:34308] 方法名-----username</span><br><span class="line">2019-12-03 14:45:38.440082+0800 DZWebLocalDemo[1554:34308] 方法名-----viewDidLoad</span><br></pre></td></tr></table></figure>

<p>   请大家对比以上，打印输出除了时间外没有任何的区别。。。。。。<br>   当然，对于带有**<font color="#b83650"><code>@property</code></font>**的属性，我们也可以重新去定义它的set方法和get方法，这样一来，达到满足自己的编程需求。</p>
<h2 id="synthesize关键字"><a href="#synthesize关键字" class="headerlink" title="@synthesize关键字"></a>@synthesize关键字</h2><p>   一直认为，**<font color="#b83650"><code>@synthesize</code></font><strong>关键字，在MRC模式下使用的更多，而目前的开发我们都是用ARC模式，很少见</strong><font color="#b83650"><code>@synthesize</code></font>**，其主要有2个作用：</p>
<ul>
<li>在MRC下，**<font color="#b83650"><code>@synthesize username</code></font><strong>这样，编译器才会自动合成str的存取方法。不过在ARC下就不必了，无论你是否</strong><font color="#b83650"><code>@synthesize username</code></font>**，编译器都会自动合成str的存取方法</li>
<li>你的属性是**<font color="#b83650"><code>username</code></font><strong>，系统会自动给你添加待下划线的成员变量是</strong><font color="#b83650"><code>_username</code></font><strong>，如果你想使用其他的成员变量替代，可以这样写</strong><font color="#b83650"><code>username = replaec_username</code></font><strong>，后面的名称是自定义的。</strong><font color="#b83650"> <code>replaec_username</code></font><strong>，而不是</strong><font color="#b83650"> <code>username</code></font>**，但是这样的意义并不大</li>
</ul>
<h2 id="readwrite，readonly关键字"><a href="#readwrite，readonly关键字" class="headerlink" title="readwrite，readonly关键字"></a>readwrite，readonly关键字</h2><p>   我们定义的属性，一般默认为**<font color="#b83650"><code>readwrite</code></font><strong>，但是有时候，我们希望能够暴露给外部的属性为可读属性，那么我们可以在</strong><font color="#b83650"><code>.h头文件</code></font><strong>写入以下的关键字</strong><font color="#b83650"><code>@property (nonatomic, strong, readonly) NSString *username;</code></font><strong>，然后这样又会引起另外一个问题，就是在</strong><font color="#b83650"><code>.m实现文件</code></font><strong>里，无法写入值，那么需要在这里再次声明一个属性不过换了一个关键字</strong><font color="#b83650"><code>@property (nonatomic, strong, readwrite) NSString *username;</code></font><strong>，这样就可以实现在</strong><font color="#b83650"><code>.h头文件</code></font><strong>外部只可读取，而内部</strong><font color="#b83650"><code>.m执行文件</code></font>**可读可写。</p>
<h2 id="nonatomic，atomic原子性"><a href="#nonatomic，atomic原子性" class="headerlink" title="nonatomic，atomic原子性"></a>nonatomic，atomic原子性</h2><p>   在默认情况下，由编译器所合成的方法会通过锁定机制确保其原子性**<font color="#b83650"><code>atomic</code></font><strong>。如果属性具备</strong><font color="#b83650"><code>nonatomic</code></font><strong>，则不需要同步锁。具备</strong><font color="#b83650"><code>atomic</code></font><strong>特质的获取方法会通过锁定机制来确保其操作的原子性。<br>   一般iOS程序中，所有属性都声明为</strong><font color="#b83650"><code>nonatomic</code></font>**。这样做的原因是：<br>在iOS中使用同步锁的开销比较大， 这会带来性能问题。一般情况下并不要求属性必须是“原子的”，因为这并不能保证“线程安全”(thread safety)，若要实现“线程安全”的操作，还需采用更为深层的锁定机制才醒。可以这样概括：</p>
<ul>
<li>atomic：原子属性，为setter方法加锁，系统默认使用atomic，线程安全，需要消耗大量资源</li>
<li>nonatomic：非原子属性，不会为setter方法加锁，非线程安全，适合内存小的移动设备</li>
</ul>
<h2 id="strong，weak，assign，copy，unsafe-unretained关键字"><a href="#strong，weak，assign，copy，unsafe-unretained关键字" class="headerlink" title="strong，weak，assign，copy，unsafe_unretained关键字"></a>strong，weak，assign，copy，unsafe_unretained关键字</h2><p>   这些关键字仅会影响属性的set方法，编译器根据不同的关键字生成不同的代码。当我们自定义set方法的时候，也应该符合属性所具备的特质。除了**<font color="#b83650"><code>assign</code></font>**可以用来修饰基本数据类型外，其他的关键字都只能用来修饰对象。<br>   **<font color="#b83650"><code>strong</code></font>**表示一种“拥有关系”。为属性设置新值的时候，设置方法会先保留新值（新值的引用计数加一），并释放旧值（旧值的引用计数减一），然后将新值赋值上去。相当于MRC下的retain。<br>   **<font color="#b83650"><code>weak</code></font>**表示一种“非拥有关系”。用weak修饰属性的时候，为属性设置新值的时候，设置方法既不会保留新值（新值的引用计数加一），也不会释放旧值（旧值的引用计数减一）。当属性所指的对象释放的时候，属性也会被置为nil。用于修饰UI控件，代理(delegate)。<br>   **<font color="#b83650"><code>assign</code></font><strong>可以同时用来修饰基本数据</strong><font color="#b83650"><code>NSInteger，CGFloat</code></font><strong>等类型和对象。当assign用来修饰对象的时候，和</strong><font color="#b83650"><code>weak</code></font><strong>类似。唯一的区别就是当属性所指的对象释放的时候，属性不会被置为</strong><font color="#b83650"><code>nil</code></font>**，这就会产生野指针。<br>   **<font color="#b83650"><code>copy</code></font><strong>修饰的属性设置新值的时候，当新值是不可变的，和strong是一模一样的。当新值是可变类型</strong><font color="#b83650"><code>Mutable</code></font><strong>，设置方法不会保留新值（新值的引用计数加一），而是对新值</strong><font color="#b83650"><code>copy</code></font><strong>一份，不会影响新值的引用计数。</strong><font color="#b83650"><code>copy</code></font><strong>常用来修饰</strong><font color="#b83650"><code>NSString</code></font>**，因为当新值是可变的，防止属性在不知不觉中被修改。<br>  **<font color="#b83650"><code>unsafe_unretained</code></font><strong>用来修饰属性的时候，和</strong><font color="#b83650"><code>assign</code></font><strong>修饰对象的时候是一模一样的。为属性设置新值的时候，设置方法既不会保留新值（新值的引用计数加一），也不会释放旧值（旧值的引用计数减一）。唯一的区别就是当属性所指的对象释放的时候，属性不会被置为</strong><font color="#b83650"><code>nil</code></font>**，这就会产生野指针，所以是不安全的。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/iOS/" rel="tag"># iOS</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
                <a href="/blog/2019/11/26/iOS%E6%B7%B1%E5%BA%A6%E9%93%BE%E6%8E%A5%E5%94%A4%E9%86%92app/" rel="next" title="iOS深度链接唤醒app">
                  <i class="fa fa-chevron-left"></i> iOS深度链接唤醒app
                </a>
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
                <a href="/blog/2019/12/27/iOS%E5%9C%A8svn%E4%B8%8A%E5%88%B6%E4%BD%9C%E7%A7%81%E6%9C%89%E5%BA%93/" rel="prev" title="iOS在svn上制作私有库">
                  iOS在svn上制作私有库 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          
    <div class="comments" id="comments"></div>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B1%9E%E6%80%A7"><span class="nav-number">1.</span> <span class="nav-text">属性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#synthesize%E5%85%B3%E9%94%AE%E5%AD%97"><span class="nav-number">2.</span> <span class="nav-text">@synthesize关键字</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#readwrite%EF%BC%8Creadonly%E5%85%B3%E9%94%AE%E5%AD%97"><span class="nav-number">3.</span> <span class="nav-text">readwrite，readonly关键字</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#nonatomic%EF%BC%8Catomic%E5%8E%9F%E5%AD%90%E6%80%A7"><span class="nav-number">4.</span> <span class="nav-text">nonatomic，atomic原子性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#strong%EF%BC%8Cweak%EF%BC%8Cassign%EF%BC%8Ccopy%EF%BC%8Cunsafe-unretained%E5%85%B3%E9%94%AE%E5%AD%97"><span class="nav-number">5.</span> <span class="nav-text">strong，weak，assign，copy，unsafe_unretained关键字</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="大钟"
      src="/blog/images/userimg.jpeg#/images/avatar.gif">
  <p class="site-author-name" itemprop="name">大钟</p>
  <div class="site-description" itemprop="description">Dazhong</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">10</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="feed-link motion-element">
    <a href="/blog/atom.xml" rel="alternate">
      <i class="fa fa-rss"></i>RSS
    </a>
  </div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/rogueandy" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;rogueandy" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/rogueandy" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;rogueandy" rel="noopener" target="_blank"><i class="fa fa-fw fa-gitee"></i>Gitee</a>
      </span>
  </div>



      </div>s

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">大钟</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v5.4.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.5.0
  </div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  
















  

  


<script>
NexT.utils.getScript('/js/src/Valine.min.js', () => {
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(item => {
    return GUEST.includes(item);
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: '4392Rm9FOc08gpKx04B1WkRH-gzGzoHsz',
    appKey: 'dNlRkwkrCHoG59nvxMyFN5CN',
    placeholder: "发表~~",
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: true,
    lang: '' || 'zh-cn',
    path: location.pathname,
    recordIP: false,
    serverURLs: ''
  });
}, window.Valine);
</script>

</body>
</html>
